package com.lphj.datainterface.controller;

import com.lphj.datainterface.handle.TCustomerHandle;
import com.lphj.datainterface.handle.TCustomerStoreHandle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


@RestController
public class ReadCustomerController {

    @Autowired
    TCustomerHandle tCustomerHandle;

    @Autowired
    TCustomerStoreHandle tCustomerStoreHandle;

    @RequestMapping("readCustomer")
    String readExcelForCustomer(@RequestParam("customerExcel") MultipartFile excel) {
        String info = "";
        int count = 0;
        boolean isExcel2003 = true;
        String fileName = excel.getOriginalFilename();
        //判断文件是否有效
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            info = "文件无效";
            return info;
        }
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = null;
        Workbook wb = null;
        try {
            is = excel.getInputStream();
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //取第一个表格
        Sheet sheet = wb.getSheetAt(0);
        count = tCustomerHandle.addTCustomer(sheet);
        //客户引入分公司
        tCustomerStoreHandle.addTCustomer();
        return "成功导入" + count + "条数据";
    }
}
